package cn.laixueit.resource.upload.controller;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.laixueit.resource.upload.po.TbFile;
import cn.laixueit.resource.upload.service.FileService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @author duxiang
 * @date 2024/2/23 13:45
 */
@RestController
@RequestMapping("/file")
@CrossOrigin
public class FileController {

    @Resource
    private FileService fileService;

    @PostMapping("upload")
    public Map<String, Object> upload(@RequestParam MultipartFile partFile, @RequestParam("dirName") String dirName) {
        try {
            String imgUrl = "";
            HashMap<String, Object> resultMap = new HashMap<>();
            InputStream inputStream = partFile.getInputStream();
            byte[] md5 = DigestUtil.md5(inputStream);
            String fileMd5 = StrUtil.join("", md5);
            // 查询文件是否存在，存在直接返回对应文件fileUrl
            TbFile tbFile = fileService.checkFile(fileMd5);
            if (ObjUtil.isNotEmpty(tbFile)) {
                imgUrl = tbFile.getFileUrl();
            } else {
                // 不存在，走上传
                tbFile = fileService.uploadFile(partFile, dirName,fileMd5);
                imgUrl = tbFile.getFileUrl();
            }
            resultMap.put("code", 0);
            resultMap.put("imgName", partFile.getOriginalFilename());
            resultMap.put("imgUrl", imgUrl);
            return resultMap;
        } catch (IOException e) {
            e.printStackTrace();
            return new HashMap<String, Object>() {
                {
                    put("code", 500);
                    put("imgName", partFile.getOriginalFilename());
                    put("imgUrl", null);
                }
            };
        }
    }
}
